using Godot;
using System;

public partial class Dummy : CharacterBody2D
{
	[Export] public int MaxHealth = 100;
	private int currentHealth;
	private TextureProgressBar healthBar;
	private Area2D hurtBox;
	private Sprite2D sprite;
	
	public override void _Ready()
	{
		currentHealth = MaxHealth;
		healthBar = GetNode<TextureProgressBar>("HealthBar");
		hurtBox = GetNode<Area2D>("HurtBox");
		sprite = GetNode<Sprite2D>("Sprite2D");
		
		// 设置血条
		healthBar.MaxValue = MaxHealth;
		healthBar.Value = currentHealth;
		
		// 连接受伤信号
		hurtBox.AreaEntered += OnHurtBoxAreaEntered;
	}
	
	private void OnHurtBoxAreaEntered(Area2D area)
	{
		// 调试信息：打印进入的区域信息
		GD.Print($"检测到区域进入: {area.Name}, 组: {string.Join(", ", area.GetGroups())}");
		
		// 检查是否是玩家的攻击区域
		if (area.IsInGroup("player_attack"))
		{
			GD.Print("确认为玩家攻击区域，造成伤害");
			TakeDamage(20); // 固定伤害值，可以后续改为从攻击区域获取
		}
		else
		{
			GD.Print("不是玩家攻击区域，忽略");
		}
	}
	


	public void TakeDamage(int damage)
	{
		currentHealth -= damage;
		currentHealth = Mathf.Max(0, currentHealth);
		
		// 更新血条
		healthBar.Value = currentHealth;
		
		// 受伤闪烁效果
		ShowHitEffect();
		
		// 打印伤害信息到控制台
		GD.Print($"木偶受到 {damage} 点伤害，剩余血量: {currentHealth}/{MaxHealth}");
		
		// 检查是否死亡
		if (currentHealth <= 0)
		{
			OnDeath();
		}
	}
	
	private void ShowHitEffect()
	{
		// 创建受伤闪烁效果
		var tween = CreateTween();
		tween.SetParallel(true);
		
		// 闪烁效果：快速变红再恢复
		tween.TweenProperty(sprite, "modulate", new Color(1, 0.3f, 0.3f, 1), 0.1f);
		tween.TweenProperty(sprite, "modulate", new Color(1, 1, 1, 1), 0.1f).SetDelay(0.1f);
	}
	
	private void OnDeath()
	{
		GD.Print("木偶被击败了！正在重置...");
		
		// 死亡闪烁效果
		var tween = CreateTween();
		tween.TweenProperty(sprite, "modulate", new Color(1, 1, 1, 0.3f), 0.2f);
		tween.TweenProperty(sprite, "modulate", new Color(1, 1, 1, 1), 0.2f);
		
		// 延迟重置血量
		GetTree().CreateTimer(0.5f).Timeout += () => {
			currentHealth = MaxHealth;
			healthBar.Value = currentHealth;
			GD.Print("木偶已重置，血量恢复满值");
		};
	}
}
